package com.realgodo.site.service.space;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.orm.Page;
import org.springside.modules.orm.hibernate.DefaultEntityManager;

import com.realgodo.site.entity.space.Space;
import com.realgodo.site.entity.space.SpaceCover;

@Service("spaceCoverManager")
@Transactional
public class SpaceCoverManager extends DefaultEntityManager<SpaceCover, Long> {

	@Autowired
	protected SessionFactory sessionFactory;
	public void saveSpaceCovers(Space space ,List<SpaceCover> spaceCovers){
		List<SpaceCover> olds = this.getSpaceCovers(space.getId(),SpaceCover.MAX_RUSULT);
		for(SpaceCover old:olds){
			this.entityDao.delete(old.getId());
		}
		for(SpaceCover spaceCover :spaceCovers){
			if(null!=spaceCover&&null!=spaceCover.getPath()&&!"".equals(spaceCover.getPath())){
				spaceCover.setSpace(space);
				this.entityDao.save(spaceCover);
			}
		}
	}
	
	public List<SpaceCover> getSpaceCovers(Long spaceId,int maxResult){
		Page<SpaceCover> page = new Page<SpaceCover>(maxResult);
		Criteria c = sessionFactory.getCurrentSession().createCriteria(
				SpaceCover.class);
			c.add(Restrictions.eq("space.id",spaceId));
		return this.entityDao.findByCriteria(page, c).getResult();
	}
}
